package com.hushan.standby.compoment;

import cn.hutool.core.thread.ThreadUtil;

import java.sql.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import static com.hushan.standby.App.LOCAL_HOST;
import static com.hushan.standby.App.SOURCE_HOST;

public class MySQLReplicaControl {

    // 数据库连接配置
    private static final String URL = "jdbc:mysql://" + LOCAL_HOST + ":3306";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "123456";

    private static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

    public static void main(String[] args) {
        // 执行 SQL 语句
        executeSQLStatements();

        // 定时监控同步状态
        startMonitoring();

        scheduler.shutdownNow();
    }

    public static void startSlave() {
        executeSQLStatements();
    }


    private static void executeSQLStatements() {
        Connection connection = null;
        Statement statement = null;

        try {
            // 加载 MySQL 驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 建立数据库连接
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

            // 创建 Statement 对象
            statement = connection.createStatement();

            // 获取当前 MySQL 实例的复制状态
            ResultSet resultSet = statement.executeQuery("SHOW SLAVE STATUS");

            if (resultSet.next()) {
                // 检查 Slave_IO_Running 和 Slave_SQL_Running 是否为 No
                String slaveIORunning = resultSet.getString("Slave_IO_Running");
                String slaveSQLRunning = resultSet.getString("Slave_SQL_Running");

                if (!"Yes".equalsIgnoreCase(slaveIORunning) || !"Yes".equalsIgnoreCase(slaveSQLRunning)) {
                    // 执行 SQL 语句
                    statement.execute("RESET MASTER");
                    System.out.println("MASTER reset.");

                    statement.execute("STOP REPLICA");
                    System.out.println("REPLICA stopped.");

                    statement.execute("RESET REPLICA");
                    System.out.println("REPLICA reset.");

                    statement.execute("CHANGE MASTER TO MASTER_HOST='" + SOURCE_HOST + "', MASTER_USER='root', MASTER_PASSWORD='123456', MASTER_AUTO_POSITION=1");
                    System.out.println("MASTER changed.");

                    statement.execute("START REPLICA");
                    System.out.println("REPLICA started.");
                }
            }
        } catch (ClassNotFoundException e) {
            System.err.println("MySQL JDBC driver not found.");
            e.printStackTrace();
        } catch (SQLException e) {
            System.err.println("Error executing SQL statements.");
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.err.println("Error closing resources.");
                e.printStackTrace();
            }
        }
    }

    private static void startMonitoring() {
        if (scheduler.isShutdown() || scheduler.isTerminated()) {
            scheduler = Executors.newScheduledThreadPool(1);
        }
        scheduler.scheduleAtFixedRate(MySQLReplicaControl::monitorReplicationStatus, 0, 5, TimeUnit.SECONDS); // 每5秒监控一次，可根据需要调整间隔时间
    }

    private static void monitorReplicationStatus() {
        Connection connection = null;

        try {
            // 加载 MySQL 驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 建立数据库连接
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

            Statement statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery("SHOW SLAVE STATUS");

            if (resultSet.next()) {
                System.out.printf("%-30s | %-50s%n", "Field", "Value");
                System.out.println("--------------------------------|--------------------------------------------------");
                for (int i = 1; i <= resultSet.getMetaData().getColumnCount(); i++) {
                    System.out.printf("%-30s | %-50s%n", resultSet.getMetaData().getColumnLabel(i), resultSet.getString(i));
                }
            } else {
                System.out.println("This MySQL server is not configured as a replication slave.");
            }
            System.out.println();
        } catch (ClassNotFoundException e) {
            System.err.println("MySQL JDBC driver not found.");
            e.printStackTrace();
        } catch (SQLException e) {
            System.err.println("Error monitoring replication status.");
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.err.println("Error closing resources.");
                e.printStackTrace();
            }
        }
    }

    public static void stopSlave() {
        Connection connection = null;
        Statement statement = null;

        try {
            // 加载 MySQL 驱动
            Class.forName("com.mysql.cj.jdbc.Driver");

            // 建立数据库连接
            connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);

            // 创建 Statement 对象
            statement = connection.createStatement();

            // 获取当前 MySQL 实例的复制状态
            ResultSet resultSet = statement.executeQuery("SHOW SLAVE STATUS");

            if (resultSet.next()) {
                // 检查 Slave_IO_Running 和 Slave_SQL_Running 是否为 No
                String slaveIORunning = resultSet.getString("Slave_IO_Running");
                String slaveSQLRunning = resultSet.getString("Slave_SQL_Running");

                if (!"No".equalsIgnoreCase(slaveIORunning) || !"No".equalsIgnoreCase(slaveSQLRunning)) {
                    statement.execute("STOP REPLICA");
                    System.out.println("REPLICA stopped.");
                }
            }

        } catch (ClassNotFoundException e) {
            System.err.println("MySQL JDBC driver not found.");
            e.printStackTrace();
        } catch (SQLException e) {
            System.err.println("Error executing SQL statements.");
            e.printStackTrace();
        } finally {
            // 关闭资源
            try {
                if (statement != null) {
                    statement.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                System.err.println("Error closing resources.");
                e.printStackTrace();
            }
        }
    }

    public static void startNotify() {
        startMonitoring();
    }
}